package com.imooc.controller;

import com.imooc.pojo.Users;
import com.imooc.pojo.vo.UsersVO;
import com.imooc.resource.FileResource;
import com.imooc.service.FdfsService;
import com.imooc.service.center.CenterUserService;
import com.imooc.utils.CookieUtils;
import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("fdfs")
public class CenterUserController extends BaseController {

    @Autowired
    private CenterUserService centerUserService;

    @Autowired
    private FileResource fileResource;

    @Autowired
    private FdfsService fdfsService;

    @PostMapping("uploadFace")
    public IMOOCJSONResult uploadFace(
            String userId,
            MultipartFile file,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        if (file == null) {
            return IMOOCJSONResult.errorMap("file cannot be null");
        }

        String iconFileName = file.getOriginalFilename();
        if (StringUtils.isBlank(iconFileName)) {
            return IMOOCJSONResult.errorMsg("文件名不能为空");
        }

        String fileNameArr[] = iconFileName.split("\\.");
        String suffix = fileNameArr[fileNameArr.length - 1];

        if (!suffix.equalsIgnoreCase("png")
                && !suffix.equalsIgnoreCase("jpg")
                && !suffix.equalsIgnoreCase("jpeg")) {
            return IMOOCJSONResult.errorMsg("图片格式不正确!");
        }

        // String path = fdfsService.upload(file, suffix);

        String path = fdfsService.uploadOSS(file, userId, suffix);

        System.out.println("上传成功!!!!");
        System.out.println("uploaded file to " + path);

        if (StringUtils.isNotBlank(path)) {

            // String finalUserFaceUrl = fileResource.getHost() + path;
            String finalUserFaceUrl = fileResource.getOssHost() + path;
            Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);
            UsersVO usersVO = convertUsersVO(userResult);

            CookieUtils.setCookie(request, response, "user", JsonUtils.objectToJson(usersVO), true);
        } else {
            return IMOOCJSONResult.errorMsg("上传头像失败");
        }
        return IMOOCJSONResult.ok();
    }

}
